package com.leyou.Controller;

import com.leyou.item.pojo.Brand;
import com.leyou.service.BrandService;
import com.leyou.pojo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 刘智博
 * @date 2022/2/25
 */
@Controller
@RequestMapping("brand")
public class BrandController {
    @Autowired
    private BrandService brandService;
    @GetMapping("page")
    public ResponseEntity<PageResult<Brand>> queryBrandByPage(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "rows", defaultValue = "5") Integer rows,
            @RequestParam(value = "sortBy", required = false) String sortBy,
            @RequestParam(value = "desc", defaultValue = "false") Boolean desc,
            @RequestParam(value = "key", required = false) String key) {
        PageResult<Brand> result = this.brandService.queryBrandByPageAndSort(page,rows,sortBy,desc, key);
        if (result == null || result.getItems().size() == 0) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        return ResponseEntity.ok(result);
    }
    /**
     * 新增品牌
     * @param brand
     * @param cids
     */
    @PostMapping
    public ResponseEntity<Void> saveBrand(Brand brand, @RequestParam("cids") List<Long> cids){
        this.brandService.saveBrand(brand, cids);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     *  品牌的修改
     * @param brand
     * @param cids
     * @return
     */
    @GetMapping
    public ResponseEntity<Void> updateBrand(@RequestParam("cids") List<Long> cids, Brand brand) {
        this.brandService.updateBrand(cids, brand);
        return ResponseEntity.status(HttpStatus.OK).body(null);
    }

    /**
     * 根据分类查询品牌
     * @param cid
     * @return
     */
    @GetMapping("cid/{cid}")
    public ResponseEntity<List<Brand>> queryBrandListByCid(@PathVariable("cid")Long cid){

        List<Brand> brandList = this.brandService.queryBrandByCategory(cid);
        if(CollectionUtils.isEmpty(brandList)){
            // 响应404
            return ResponseEntity.badRequest().build();
        }
        // 响应200
        return ResponseEntity.ok(brandList);
    }
    /**
     * 根据品牌id查询品牌
     * @param bid
     * @return
     */
    @GetMapping("{bid}")
    public ResponseEntity<Brand> queryBrandById(@PathVariable("bid")Long bid){
        Brand brand = this.brandService.queryBrandById(bid);
        if(brand==null){
            // 响应404
            return ResponseEntity.badRequest().build();
        }
        // 响应200
        return ResponseEntity.ok(brand);
    }
}
